# Copyright 2007, 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import svn.core

import gvn.cmdline
import gvn.util
import gvn.wc


helptext__gvn_opened = """opened: List locally modified files.
usage: opened
"""


def Handle_GvnOpened(ctx):
  changebranches = {}
  ctx.wc.Open([ctx.path])

  path_to_change_name = ctx.wc.MapPathToChangeName()
  # XXX(epg): Hmm, seems to me the callback ought to be receiving a
  # pool, like most callbacks.  Fine, we'll handle it ourselves.
  pool = svn.core.Pool(ctx.pool)
  def cb(target, status):
    pool.clear()
    # We're only interested in Modified or Broken paths.
    if gvn.wc.IsModified(status) or gvn.wc.IsBroken(status):
      target = ctx.wc.RelativePath(target)
      string = gvn.wc.StatusString(ctx.DisplayPath(target), status)
      try:
        change_name = path_to_change_name[target]
      except KeyError:
        # This path is not on any changebranch; print it now.
        print ' ' + string
      else:
        # This path is on a changebranch; save output for later.
        code = [' ', '*'][ctx.wc.NeedsSnapshot(change_name, target, status,
                                               pool)]
        string = code + string
        try:
          changebranches[change_name][target] = string
        except KeyError:
          # First time we see this changebranch; changebranches has no
          # change_name key yet: create it.
          changebranches[change_name] = {target: string}
  ctx.wc.Status([ctx.path], recursive=True, get_all=False, no_ignore=False,
                show_children=False, callback=cb)

  # Now we'll print status for each changebranched file.
  for changename in sorted(changebranches.iterkeys()):
    print "--- Changebranch %s@%d" % (changename, ctx.wc.change_state[changename].snap_revision)
    for target in sorted(changebranches[changename].iterkeys()):
      print changebranches[changename][target]

  return 0

gvn.cmdline.AddCommand('opened', Handle_GvnOpened, helptext__gvn_opened)
